﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.IO;
using vsXPathSDK;

namespace vsXPathTester.Lib
{
    /// <summary>
    /// Help loading plugin to system.
    /// </summary>
    public static class PluginSystem
    {
        private static Collection<dynamic> fileFilterPlugin = new Collection<dynamic>();
        private static Collection<dynamic> importExportPlugin = new Collection<dynamic>();

        public static dynamic[] FileFilterPlugins { get { return fileFilterPlugin.ToArray(); } }
        public static dynamic[] IMPlugins { get { return importExportPlugin.ToArray(); } }

        public static void InitalizePlugins()
        {
            string dir = Path.GetDirectoryName(Assembly.GetAssembly(typeof(PluginSystem)).Location);
            try
            {
                if (!System.IO.Directory.Exists(dir + "\\plugins\\"))
                    System.IO.Directory.CreateDirectory(dir + "\\plugins\\");
                foreach (string file in System.IO.Directory.GetFiles(dir + "\\plugins\\", "*.dll", System.IO.SearchOption.AllDirectories))
                {
                    if (file.EndsWith(".dll"))
                    {
                        Assembly dll = Assembly.LoadFrom(file);
                        foreach (Type t in dll.GetTypes())
                        {
                            try
                            {
                                if (t.BaseType.FullName == typeof(FileFilterPlugin).FullName)
                                {
                                    fileFilterPlugin.Add((dynamic)Activator.CreateInstance(t));
                                    continue;
                                }
                                else if (t.BaseType.FullName == typeof(ImportExportPlugin).FullName)
                                {
                                    importExportPlugin.Add((dynamic)Activator.CreateInstance(t));
                                    continue;
                                }
                            }
                            catch (Exception) { }
                        }
                        dll = null;
                    }
                }
                GC.Collect();
            }
            catch
            {
                throw;
            }
        }
    }
}
